package com.oceansoft.mobile.econsole.weixin.controller;

import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by xuhb on 2016/7/6.
 */

@Controller
@RequestMapping("weixin/key")
public class KeyController extends BaseController{

    @RequestMapping(value="check")
    @ResponseBody
    public String jiaojing(HttpServletRequest request) throws Exception{
        String siteCode = request.getParameter("siteCode");
        String version = request.getParameter("version");
        String transacCode = request.getParameter("transacCode");
        String repData = request.getParameter("repData").replaceAll(" ","+");
        String signStr = request.getParameter("signStr");
        return isOk(siteCode,version,transacCode,repData,signStr);
    }

    @RequestMapping(value="encypt")
    @ResponseBody
    public String encypt(HttpServletRequest request) throws Exception{
        String respCode = request.getParameter("respCode");
        String respMsg = request.getParameter("respMsg");
        String respData = request.getParameter("respData");
        return encyptRsa(respCode,respMsg,respData);
    }

    public static String isOk(String siteCode,String version,String transacCode,String  repData,String signStr) {
        try {
            byte[] sign = Base64.decodeBase64(Base64.decodeBase64(signStr));
            String oriRepData=new String(Base64.decodeBase64(repData),"UTF-8");
            String data= siteCode+version+transacCode+oriRepData;
            String publicKeystr="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUdF1UjSdjPfsboSCoReIQkLGiZsU/4GEXO7cBsaxL1KW4FQ26GrRFxn35hwgJvKLIdYAVEVjZUacY7dPZwc9hEQqmv7or0vjFIO/QC/EsPxPHbRI7d+uXE5CtmIu71F04baezw9x+wMU2LKy8ouHC4InxV5l0CqyiwbxHl4+9lQIDAQAB";
            byte[]publicKey=Base64.decodeBase64(publicKeystr);//对提供的公钥做 base64 解
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey pubKey = keyFactory.generatePublic(keySpec) ;
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(pubKey);
            signature.update(data.getBytes("UTF-8"));
            boolean ok= signature.verify(sign);
            if(ok){
                return "1";
            }else{
                return "0";
            }
        }
        catch ( Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    public String encyptRsa(String respCode,String respMsg,String respData)
    {
        try {
            String prikeyStr="MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAJqjQa2taahYFSTAlMnHz+7OwNm8\n" +
                    "8ypyv+wJQZ8adcOI6M4CgHAtwXNFk/r4WenBdmDPR4q4Y8tDmpp5kD+PcFS4pNdxzva8AALUUXHi\n" +
                    "HujKXd31eupTJhrNIyHlTlqxGIgIfVU3e2V7V3ExTOdnqejYtFQTzc5flEu9cofoZpQxAgMBAAEC\n" +
                    "gYEAlpMXlg1Az8qNNA9OEjk9cLTkNmD1isTXuve8bTdvqmm6/zaSaCk1sI/0qzF/I83c/iF38Uzg\n" +
                    "54E5nud2HV4HqwPmEF4+MzduroBu/CRQtIHjHVU3JC7imc0pFHUxNLNmAr+qndX7AWE82TVROLYk\n" +
                    "TuYGZ9xZhl2i+sdaNPl3chECQQDJ/cgaMxPKsUwRkNa1M6biTVk9iR0p2PNiR+AoYZct94NYZ1qa\n" +
                    "S+6Cf4SvdYUtZj43QtmnyQI9rU/mP95LlBQVAkEAw/wkC3qFLEtdT0nljqmBC/EWMZgi+i+hQCMw\n" +
                    "tCMFX0dL3vKmnOCNGmElkD7JVxdxSZy3NOXaY5UvhlH2tnd6rQJASh8Pe9W8cIfJAzUkJNA0cBy0\n" +
                    "H6meAwoynaEEd60AHgUStLEQhUhR2J9UoFI+sZ8wO3UTi8duRBXCGRrcxt0q1QJBAJLT9QEwglMk\n" +
                    "Bz0exL+z1/1lWlY/f3zmcC1H7/YVArJWDM50BkUjqjLoMyc1EsyPwI0AvvT/ezT+EMPV5jrfmmUC\n" +
                    "QQCYJ3U2u/J/zrk0osoY5Cw26gX89OR1rFTIlXcmstV+hmlAH6A7ccJHuLm9dmwWOuBsDwytVYVb\n" +
                    "5I7lH2wFuynv";

            /*String prikeyStr="MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAJqjQa2taahYFSTAlMnHz+7OwNm8" +
                    "8ypyv+wJQZ8adcOI6M4CgHAtwXNFk/r4WenBdmDPR4q4Y8tDmpp5kD+PcFS4pNdxzva8AALUUXHi" +
                    "HujKXd31eupTJhrNIyHlTlqxGIgIfVU3e2V7V3ExTOdnqejYtFQTzc5flEu9cofoZpQxAgMBAAEC" +
                    "gYEAlpMXlg1Az8qNNA9OEjk9cLTkNmD1isTXuve8bTdvqmm6/zaSaCk1sI/0qzF/I83c/iF38Uzg" +
                    "54E5nud2HV4HqwPmEF4+MzduroBu/CRQtIHjHVU3JC7imc0pFHUxNLNmAr+qndX7AWE82TVROLYk" +
                    "TuYGZ9xZhl2i+sdaNPl3chECQQDJ/cgaMxPKsUwRkNa1M6biTVk9iR0p2PNiR+AoYZct94NYZ1qa" +
                    "S+6Cf4SvdYUtZj43QtmnyQI9rU/mP95LlBQVAkEAw/wkC3qFLEtdT0nljqmBC/EWMZgi+i+hQCMw" +
                    "tCMFX0dL3vKmnOCNGmElkD7JVxdxSZy3NOXaY5UvhlH2tnd6rQJASh8Pe9W8cIfJAzUkJNA0cBy0" +
                    "H6meAwoynaEEd60AHgUStLEQhUhR2J9UoFI+sZ8wO3UTi8duRBXCGRrcxt0q1QJBAJLT9QEwglMk" +
                    "Bz0exL+z1/1lWlY/f3zmcC1H7/YVArJWDM50BkUjqjLoMyc1EsyPwI0AvvT/ezT+EMPV5jrfmmUC" +
                    "QQCYJ3U2u/J/zrk0osoY5Cw26gX89OR1rFTIlXcmstV+hmlAH6A7ccJHuLm9dmwWOuBsDwytVYVb" +
                    "5I7lH2wFuynv";*/
            String oriRepData=new String(Base64.decodeBase64(respData),"UTF-8");
            String data= respCode+respMsg+oriRepData;
            byte[] keyBytes = Base64.decodeBase64(prikeyStr.getBytes());//对私钥做 base64 解码

            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec) ;

            Signature signature = Signature.getInstance("MD5withRSA");

            signature.initSign(priKey);

            signature.update(data.getBytes("UTF-8"));//data 为要生成签名的源数据字节数组

            String result= Base64.encodeBase64String(Base64.encodeBase64String(signature.sign()).getBytes());
            return  result;
        } catch ( Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
